var Web3 = require('web3')
var solc = require('solc')
var fs = require('fs')
var path = require('path')
var _async = require('asyncawait/async')
var _await = require('asyncawait/await')

var filePath = path.join(__dirname, 'contract.sol')
console.log('filePath:', filePath)

_async(() => {
    const input = fs.readFileSync(filePath)
    const output = solc.compile(input.toString(), 1)
    console.log('Output::', output)
    const bytecode = output.contracts[':FileManager'].bytecode
    console.log('Interface::', output.contracts[':FileManager'].interface)
    const abi = JSON.parse(output.contracts[':FileManager'].interface)

    web3 = new Web3('ws://localhost:8546')
    var fromUser = _await(web3.eth.getAccounts())[0]
    _await(web3.eth.personal.unlockAccount(fromUser, '123'))
    console.log('FromUser:' + fromUser)
    var fileManagerContract = new web3.eth.Contract(abi)
    console.log('Deploy contract ....')
    _await(
        fileManagerContract
            .deploy({
                data: '0x' + bytecode
            })
            .send({
                from: fromUser,
                gas: 4700000
            })
            .on('receipt', function(receipt) {
                console.log('Contract mined ! address::', receipt)
            })
            .on('mined', function(receipt) {
                console.log('Contract mined  2 ! address::', receipt)
            })
    )
})()
